﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using PPFinance.Downloader.AssemblySvr;
using PPFinance.Common;
using System.IO.IsolatedStorage;
using System.IO;
using System.Windows.Threading;
using System.Reflection;

namespace PPFinance.Downloader
{
    public partial class MainPage : UserControl
    {
        public MainPage()
        {
            InitializeComponent();

            this.Loaded += new RoutedEventHandler(MainPage_Loaded);
        }

        void MainPage_Loaded(object sender, RoutedEventArgs e)
        {
            using (IsolatedStorageFile file = IsolatedStorageFile.GetUserStoreForApplication())
            {
                if (file.Quota < 100 * 1024 * 1024)
                {
                    Space winSpace = new Space();
                    winSpace.Closed += new EventHandler(winSpace_Closed);
                    winSpace.Show();
                }
                else
                { DownLoadInfo(); }
            }

        }

        void winSpace_Closed(object sender, EventArgs e)
        {
            DownLoadInfo();

        }
        void DownLoadInfo()
        {
            AssemblyDownLoadClient client = new AssemblyDownLoadClient();
            client.GetAssemblyDataCompleted += new EventHandler<GetAssemblyDataCompletedEventArgs>(client_GetAssemblyDataCompleted);
            client.GetAssemblyDataAsync();
        }
        void client_GetAssemblyDataCompleted(object sender, GetAssemblyDataCompletedEventArgs e)
        {
            List<string> waitList = new List<string>();
            foreach (var item in e.Result)
            {
                waitList.Add(item.DownloadUrl);
                new Common.DownLoader(item.DownloadUrl,
                    (string url, DownloadProgressChangedEventArgs pe) =>
                    {
                        txtInfo.Text += "\r\n" + "下载:" + url + "，总计：" + pe.TotalBytesToReceive + ",已下载：" + pe.BytesReceived + ",完成:" + pe.ProgressPercentage + "%";
                        return null;
                    },
                    (string url, OpenReadCompletedEventArgs re) =>
                    {
                        FileAction fa = new FileAction();
                        fa.Save(re.Result, System.IO.Path.GetFileName(url), "Assembly");
                        waitList.Remove(url);
                        txtInfo.Text += "\r\n" + "下载完成:" + url;
                        return null;
                    }).Read();

            }
            DispatcherTimer timer = new DispatcherTimer();
            timer.Interval = TimeSpan.FromSeconds(1);

            timer.Tick += (object tsender, EventArgs te) =>
            {
                if (waitList.Count < 1)
                {
                    timer.Stop();
                    //Dispatcher.BeginInvoke(Init_Assembly);
                    Init_Assembly();
                }
            };
            timer.Start();
        }
        private List<Assembly> assList = new List<Assembly>();

        [System.Security.SecurityCriticalAttribute()]
        private void Init_Assembly()
        {
            FileAction fa = new FileAction();
            foreach (var dll in fa.GetFiles("Assembly"))
            {
                AssemblyPart assp = new AssemblyPart();

                string filePath = System.IO.Path.Combine("Assembly", dll);
                assList.Add(assp.Load(fa.BytesToStream(fa.GetData(filePath))));
            }
            var assStaticFilter = assList.Where(p => p.FullName == "PPFinance.UI.Static, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");
            if (assStaticFilter.Any())
            {
                var ass = assStaticFilter.Single();
                ass.GetType("PPFinance.UI.Static.ClientVariable").GetField("ClientAssembly", BindingFlags.Static | BindingFlags.Public).SetValue(null, assList);

            }
            var assUIMainFilter = assList.Where(p => p.FullName == "PPFinance.UI, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null");
            if (assUIMainFilter.Any())
            {
                var ass = assUIMainFilter.Single();
                var mainControl = ass.CreateInstance("PPFinance.UI.ThemeContainer") as UserControl;
                MainContainer.Children.Add(mainControl);
            }
         
        
        }
    }
}
